package com.banciyuan.bcywebview.biz.circles.smooth.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CircleApi;
import com.banciyuan.bcywebview.base.fragment.BaseFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreashRecycleView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.biz.circles.smooth.adapter.CircleSmoothTopUserAdapter;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.ActiveUser;
import de.greenrobot.daoexample.model.PostRank;

/**
 * Created by squall on 2016/9/30.
 */

public class CircleSmoothUserTopFragment extends BaseFragment {

    public final static String COSER = "coser";
    public final static String DRAWER = "drawer";
    public final static String WRITER = "writer";
    public final static String COSERMORE = "cosermore";
    public final static String DRAWERMORE = "drawermore";
    public final static String WRITERMORE = "writermore";
    public final static String COSERTITLE = "cosertitle";
    public final static String DRAWERTITLE = "drawertitle";
    public final static String WRITERTITLE = "writertitle";

    private Map<String, Integer> map = new HashMap<>();
    private CircleSmoothTopUserAdapter mAdapter;
    private PullToRefreashRecycleView refreashRecycleView;
    private RecyclerView recyclerView;
    private List<ActiveUser> alist = new ArrayList<>();
    private String id;
    private RequestQueue queue;

    private View mProgressbarView;
    private ProgressbarHelper mProgressbarHelper;

    private boolean loading;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.topuser_layout, null);
        initArgs();
        initProgressbar(view);
        initUi(view);
        initAction();
        initData();
        return view;
    }

    @Override
    protected void initArgs() {
        Bundle args = getArguments();
        id = args.getString("id");
        queue = VolleyQueue.getRquest(getActivity());
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    mProgressbarHelper.onLoading();
                    loading = true;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View view) {
        refreashRecycleView = (PullToRefreashRecycleView) view.findViewById(R.id.timeline_refresh_lv);
        recyclerView = refreashRecycleView.getRefreshableView();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        mAdapter = new CircleSmoothTopUserAdapter(getActivity(), alist, map, id);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void initAction() {
        refreashRecycleView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                loading = false;
                initData();
            }
        });
    }

    @Override
    protected void initData() {
        if (loading) return;
        String url = HttpUtils.BASE_URL + CircleApi.getPostRank();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        pairs.add(new BcyPair(HttpUtils.ID, id));
        HashMap<String, String> map = HttpUtils.getData(pairs);

        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        Gson gson = new Gson();
                        PostRank postRank = gson.fromJson(result.toString(), PostRank.class);
                        renderData(tranFormData(postRank));
                    } catch (Exception e) {
                        loading = false;
                        mProgressbarHelper.onFailed();
                        refreashRecycleView.onRefreshComplete();
                    }
                } else {
                    loading = false;
                    mProgressbarHelper.onFailed();
                    refreashRecycleView.onRefreshComplete();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                loading = false;
                mProgressbarHelper.onFailed();
                refreashRecycleView.onRefreshComplete();

            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(requestParam);
    }

    private List<ActiveUser> tranFormData(PostRank postRank) {
        List<ActiveUser> alist = new ArrayList<>();
        alist.add(new ActiveUser(DRAWERTITLE));

        for (int i = 0; i < postRank.getDrawer().size(); i++) {
            ActiveUser a = postRank.getDrawer().get(i);
            a.setType(DRAWER);
            a.setIndex(i);
            alist.add(a);
        }
        if (postRank.getDrawer().size() >= 3) {
            alist.add(new ActiveUser(DRAWERMORE));
        }
        alist.add(new ActiveUser(WRITERTITLE));
        for (int i = 0; i < postRank.getWriter().size(); i++) {
            ActiveUser a = postRank.getWriter().get(i);
            a.setType(WRITER);
            a.setIndex(i);
            alist.add(a);
        }

        if (postRank.getWriter().size() >= 3) {
            alist.add(new ActiveUser(WRITERMORE));
        }

        alist.add(new ActiveUser(COSERTITLE));
        for (int i = 0; i < postRank.getCoser().size(); i++) {
            ActiveUser a = postRank.getCoser().get(i);
            a.setType(COSER);
            a.setIndex(i);
            alist.add(a);
        }
        if (postRank.getCoser().size() >= 3) {
            alist.add(new ActiveUser(COSERMORE));
        }
        map.put(DRAWER, postRank.getDrawer().size());
        map.put(WRITER, postRank.getWriter().size());
        map.put(COSER, postRank.getCoser().size());

        return alist;
    }

    private void renderData(List<ActiveUser> templist) {
        alist.clear();
        alist.addAll(templist);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter = new CircleSmoothTopUserAdapter(getActivity(), alist, map, id);
            recyclerView.setAdapter(mAdapter);
        }
        refreashRecycleView.onRefreshComplete();
        mProgressbarHelper.onSuccess();
        loading = false;
    }

}
